package com.supermap.fabricsdk;

import org.hyperledger.fabric.sdk.*;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;

import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Logger;

/**
 * 交易处理接口实现类
 */
class SmTransactionImp implements SmTransaction {

    Logger logger = Logger.getLogger(SmTransactionImp.class.toString());
    private HFClient hfClient;
    private Channel channel;
    private Collection<ProposalResponse> successful = new LinkedList<>();
    private Collection<ProposalResponse> failed = new LinkedList<>();
    private Collection<ProposalResponse> proposalResponses = new LinkedList<>();

    public SmTransactionImp(HFClient hfClient, Channel channel) {
        this.hfClient = hfClient;
        this.channel = channel;
    };

    /**
     * 根据返回信息 message = "execute chaincode successfully" 进行判断交易有没有执行，执行1000次，不成功返回错误提示信息
     * 查询
     * @param chaincodeName 链码名称
     * @param functionName  方法名称
     * @param args  参数
     * @return  查询结果
     */
    @Override
    public synchronized String queryByString(String chaincodeName, String functionName, String[] args) {
        StringBuilder stringBuilder = new StringBuilder();
        TransactionProposalRequest queryByChaincodeRequest = FabricsdkUtils.getTransactionProposalRequest(hfClient, chaincodeName, functionName, args);
        int count = 0;
        boolean cn = true;
        while (cn) {
            try {
                // 发送交易提案
                proposalResponses = channel.sendTransactionProposal(queryByChaincodeRequest);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (proposalResponses == null) {
                return "No Response";
            }
            for (ProposalResponse res : proposalResponses) {
                if ( res.getStatus() == ProposalResponse.Status.SUCCESS) {
                    cn = false;
                } else {
                    count++;
                    if(count >= 10){
                        return "query failed";
                    }
                    logger.info(res.getMessage());
                    continue;
                }
                try {
                    String str = new String(res.getChaincodeActionResponsePayload(), "utf-8");
                    stringBuilder.append(str);
                } catch (InvalidArgumentException | UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 查询键为 byte[] 格式的值
     * @param chaincodeName 链码名称
     * @param functionName  方法名称
     * @param args  参数
     * @return  查询结果
     */
    @Override
    public byte[][] queryByByte(String chaincodeName, String functionName, byte[][] args) {

        String message = "";
        int count = 0;
        byte[][] bytes = null;
        ArrayList<byte[]> byteArrayList = new ArrayList<>();
        TransactionProposalRequest queryByChaincodeRequest = FabricsdkUtils.getTransactionProposalRequest(hfClient, chaincodeName, functionName, args);
        try {
            // 发送交易提案
            proposalResponses = channel.sendTransactionProposal(queryByChaincodeRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (proposalResponses == null) {
            return new byte[][]{"No Response".getBytes()};
        }
        // 将结果构造为 byte[][]
        for (ProposalResponse res : proposalResponses) {
            try {
                byteArrayList.add(res.getChaincodeActionResponsePayload());

            } catch (InvalidArgumentException e) {
                e.printStackTrace();
            }
        }
        bytes = byteArrayList.toArray(new byte[1][byteArrayList.size()]);
        return bytes;
    }

    /**
     * 执行链码
     * @param chaincodeName 链码名称
     * @param functionName  方法名称
     * @param args  参数
     * @return  执行结果
     */
    @Override
    public synchronized String invokeByString(String chaincodeName, String functionName, String[] args) {
        String transactionID = "";
        proposalResponses = null;
        TransactionProposalRequest transactionProposalRequest = FabricsdkUtils.getTransactionProposalRequest(hfClient, chaincodeName, functionName, args);
        int count = 0;
        boolean cn = true;
        while (cn) {
            try {

                // 1、直接发送
                proposalResponses = channel.sendTransactionProposal(transactionProposalRequest);


                ///2、TODO Fabric 服务发现机制
//            Channel.DiscoveryOptions discoveryOptions = Channel.DiscoveryOptions.createDiscoveryOptions();
//            discoveryOptions.setEndorsementSelector(ServiceDiscovery.EndorsementSelector.ENDORSEMENT_SELECTION_RANDOM);
//////            ENDORSEMENT_SELECTION_RANDOM: 随机选取满足背书策略的peer节点组合
//////            ENDORSEMENT_SELECTION_LEAST_REQUIRED_BLOCKHEIGHT: 选取满足背书策略的，状态最新、块高最大的peer节点组合
//            discoveryOptions.setForceDiscovery(false);
//////            true: 每一次发送proposal时都调用discovery服务获取peer列表，会有一定的资源消耗
//////            false: 发送proposal时使用discovery服务缓存的peer列表，默认2分钟刷新一次
//            discoveryOptions.setInspectResults(true);
////            true: 关闭 SDK 背书策略检查，由应用逻辑进行判断
////            false: SDK 自动进行背书策略检查，不满足抛出异常

                // 向所有背书节点发送交易，成功后返回要发往排序节点的提案
                // 随机执行一个节点来执行
//            proposalResponses = channel.sendTransactionProposal(transactionProposalRequest);
//            proposalResponses = channel.sendTransactionProposal(transactionProposalRequest, channel.getPeers());

                // 3、随机选择一个 peer 节点发送交易即可
//            Collection<Peer> peers = channel.getPeers(EnumSet.of(Peer.PeerRole.ENDORSING_PEER));
//            int size = peers.size();
//            Random random = new Random();
//            int index = random.nextInt(size);
//            Peer[] endorsingPeers = new Peer[size];
//            peers.toArray(endorsingPeers);
//            Set partialPeers = new HashSet();
//            partialPeers.add(endorsingPeers[index]);
//            proposalResponses = channel.sendTransactionProposal(transactionProposalRequest, partialPeers);

                // 判断背书结果
                for (ProposalResponse response : proposalResponses) {
                    if (response.getStatus() == ProposalResponse.Status.SUCCESS) {
                        successful.add(response);
                        transactionID = response.getTransactionID();
                        cn = false;
                    } else {
                        count++;
                        if(count >= 10){
                            return "invoke failed";
                        }
                        failed.add(response);
                        continue;
                    }
                }
                // 对背书结果的判断
                if (failed.size() > 0) {
                    ProposalResponse firstTransactionProposalResponse = failed.iterator().next();
                    logger.info("Not enough endorsers for invoke:" + failed.size() + " endorser error: " +
                            firstTransactionProposalResponse.getMessage() +
                            ". Was verified: " + firstTransactionProposalResponse.isVerified());
                }
                // 向排序节点发送背书后的交易提案，成功后返回一个区块事件
                CompletableFuture<BlockEvent.TransactionEvent> completableFuture = channel.sendTransaction(proposalResponses);
                if (completableFuture.isDone() == true) {
                    logger.info("区块分发交易失败");
                    transactionID = "";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return transactionID;
    }

    /**
     * 执行链码，参数为 byte[] 格式
     * @param chaincodeName 链码名称
     * @param functionName  方法名称
     * @param args  参数
     * @return  执行结果
     */
    @Override
    public String invokeByByte(String chaincodeName, String functionName, byte[][] args) {
        StringBuilder stringBuilder = new StringBuilder();
        TransactionProposalRequest transactionProposalRequest = FabricsdkUtils.getTransactionProposalRequest(hfClient, chaincodeName, functionName, args);
        try {
            // 发送交易提案
            proposalResponses = channel.sendTransactionProposal(transactionProposalRequest);
            // 判断背书结果
            for (ProposalResponse response : proposalResponses) {
                if (response.getStatus() == ProposalResponse.Status.SUCCESS) {
                    successful.add(response);
                } else {
                    failed.add(response);
                }
            }
            // 对背书结果的判断
            if (failed.size() > 0) {
                ProposalResponse firstTransactionProposalResponse = failed.iterator().next();
                logger.info("Not enough endorsers for invoke:" + failed.size() + " endorser error: " +
                        firstTransactionProposalResponse.getMessage() +
                        ". Was verified: " + firstTransactionProposalResponse.isVerified());
            } else {
                stringBuilder.append("successfully");
            }
            // 向排序节点发送背书后的交易提案，成功后返回一个区块事件
            CompletableFuture<BlockEvent.TransactionEvent> completableFuture = channel.sendTransaction(proposalResponses);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
}
